﻿<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="CreateDesignForm.aspx.cs" Inherits="ZX.WebApp.DesignForm.CreateDesignForm" %>
<%@ Register Assembly="CKEditor.NET" Namespace="CKEditor.NET" TagPrefix="CKEditor" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head id="Head1" runat="server">
    <title></title>
    <!--CSS file (default YUI Sam Skin) -->
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/reset-fonts-grids/reset-fonts-grids.css" />
   <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/container/assets/skins/sam/container.css" />
   <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/menu/assets/skins/sam/menu.css" />
   <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/button/assets/skins/sam/button.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/resize/assets/skins/sam/resize.css" />
    <link rel="stylesheet" type="text/css" href="../scripts/yui_2.9.0/build/layout/assets/skins/sam/layout.css" />
 <link type="text/css" rel="stylesheet" href="../Scripts/yui_2.9.0/build/datatable/assets/skins/sam/datatable.css" />
    <!--begin custom header content for this example-->
    <style type="text/css">
    .yui-skin-sam table {
	    width: 100%;
    }
    
    #button-example-form fieldset, 
    #button-example-form fieldset div {

        border: 2px groove #ccc;
        margin: .5em;
        padding: .5em;

    }

    .yui-button#pushbutton2 button,
    .yui-button#pushbutton5 button, 
    .yui-button .Add button {
        background: url(../button/assets/add.gif) center center no-repeat;
        text-indent: -4em;
        overflow: hidden;
        padding: 0 .75em;
        width: 2em;
        *margin-left: 4em;   /* IE only */
        *padding: 0 1.75em;  /* IE only */

    }
    
    .yui-button#pushbutton3 button,
    .yui-button#pushbutton6 button, 
    .yui-button#pushbutton9 button {

        padding-left: 2em;
        background: url(../button/assets/add.gif) 10% 50% no-repeat;
    
    }
    #container select,#container input
    {
        width:100%;
        min-width:5em;
    }
    
    
    #toolbar
    {
        border-bottom:1px solid #ccc;
        margin-bottom:3px;
    }
    .form
    {
        padding:5px;
    }
    
    .form select
    {
        width:120px;
    }
    
    
</style>
    <!--end custom header content for this example-->
    <!-- Dependencies -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/yahoo-dom-event/yahoo-dom-event.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/element/element-min.js"></script>
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datasource/datasource-min.js"></script>
    <!-- OPTIONAL: JSON Utility (for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/json/json-min.js"></script>
    <!-- OPTIONAL: Connection Manager (enables XHR for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/connection/connection-min.js"></script>
    <!-- OPTIONAL: Get Utility (enables dynamic script nodes for DataSource) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/get/get-min.js"></script>
    <!-- OPTIONAL: Drag Drop (enables resizeable or reorderable columns) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/dragdrop/dragdrop-min.js"></script>
    <!-- OPTIONAL: Calendar (enables calendar editors) -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/calendar/calendar-min.js"></script>
    <!-- Source files -->
    <script type="text/javascript" src="../Scripts/yui_2.9.0/build/datatable/datatable-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/layout/layout-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/button/button-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/container/container-min.js"></script>
    <script type="text/javascript" src="../scripts/yui_2.9.0/build/resize/resize-min.js"></script>
    <script src="../Scripts/Appjs/model.TrSubjectInfo.js" type="text/javascript"></script>
    <script src="../ckeditor/ckeditor.js" type="text/javascript"></script>
    <script src="../Scripts/jquery-1.6.min.js" type="text/javascript"></script>
    <script src="../Scripts/jquery.json-2.2.min.js" type="text/javascript"></script>
    <script src="../Scripts/Jquery/jlinq/jlinq.js" type="text/javascript"></script>
    <script src="../Scripts/Jquery/DesignForm/DesignForm.Common.js" type="text/javascript"></script>
    <script src="DesignForm.js" type="text/javascript"></script>
    <script type="text/javascript">
	//<![CDATA[

        // The instanceReady event is fired, when an instance of CKEditor has finished
        // its initialization.

    </script>
</head>
<body>
    <form id="form1" runat="server">
    <div>
      <div id="contents" class="yui-skin-sam">
        <div id="toolbar" style="padding: 5px;">
            <%--        <button type="button" id="btnOpen" class="yui-button yui-push-button" style="display: none">
            打开方案</button>--%>
            表单名：<input id="txtFormName" type="text" onchange="txtFormName_ChangeEvent(this)" />
            选表：<select id="setTable" onchange='setTable_ChangeEvent(this);'>
                <option></option>
            </select>
            <button type="button" id="btnSave" class="yui-button yui-push-button">
                生成表单</button>
        </div>
        <div class="form" style="display: none"> 
        </div>
        <div id="container">
        </div>
    </div>

      <div id="divEditor" style="display: none" >
        <CKEditor:CKEditorControl ID="editor1" runat="server" Height="500" >

        </CKEditor:CKEditorControl>
 	

		<script type="text/javascript">
		//<![CDATA[
		    // Replace the <textarea id="editor1"> with an CKEditor instance.
		    var editor = CKEDITOR.replace('editor1');
	
		//]]>
		</script>
     </div>
    </div>


    <script type="text/javascript">

        // 字段信息
        // { Text: "日期", Value: "yui-date" },          
        var arrOperation = [{ Text: "单行文本", Value: "textfield" },
         { Text: "多行文本", Value: "textarea" },
         { Text: "单选框", Value: "radio" },
         { Text: "复选框", Value: "checkbox" },
        { Text: "下拉选择框", Value: "select" },
        { Text: "内部用户", Value: "u" },
        { Text: "外部用户", Value: "t" },
        { Text: "职员", Value: "e" },
        { Text: "部门", Value: "s" },
        { Text: "客户", Value: "m" },
        { Text: "客户经理", Value: "v" },
        { Text: "业绩归属", Value: "g" },
        { Text: "客户总监", Value: "h" }
        ],
         arrCType = [{ Text: "字符串", Value: "string" },
         { Text: "小数", Value: "decimal" },
         { Text: "整数", Value: "int" },
         { Text: "日期", Value: "datetime" }
        ],
         arrCanNull = [{ Text: "可选", Value: "empty" },
         { Text: "必填", Value: "required" }
        ],
        const_SolutionList = null,
        const_EntityName = '',
        _MasterData = [],
        _FormID = '',
        _FormName = '',
        _MasterTableName = '',
        _TemplateName = '<%=TemplateName %>',
        _MasterJson = '',
        _DetailsJson = '',
        oCKeditor,
         html = '',
        _SelectArray= null;


        function createEditor(formName, masterTableName, strJson) {
            if (oCKeditor)
                return;
            oCKeditor = editor;
            oCKeditor.on('change', function (e) {
                var formHtml = oCKeditor.getData();
                SelectRegular(formHtml);

            });

            if (oCKeditor.name == 'editor1') {
                var command = editor.getCommand('maximize');
                command.exec();
            }


//            CKEDITOR.on('instanceReady', function (event) {
//                var editor = event.editor;

//                setTimeout(function () {
//                    // Delay bit more if editor is still not ready.
//                    if (!editor.element) {
//                        setTimeout(arguments.callee, 100);
//                        return;
//                    }
//                    event.removeListener('instanceReady', this.callee);
//                    if (editor.name == 'editor1') {
//                        var command = editor.getCommand('maximize');
//                        command.exec();
//                    }
//                }, 0);
//            }, null, null, 9999);
            _SelectArray = new Array();
 
            DIF.init(_FormID, _FormName, _MasterTableName, _TemplateName);
            DIF.CodeSmithExplorer.init(formName, masterTableName, strJson);
        }

        //    function setTableName() {
        //    var tbname = '';
        //    tbname = $("#ddltable option:selected").text();
        //    if (tbname != '') {
        //        _MasterTableName = tbname;
        //        DIF.MasterData.init();
        //    }

        //         arrOrAnd = [ { Text: " ", Value: " " },{ Text: "是", Value: "Y" }, { Text: "否", Value: "N" }],
        //        mDataTable,
        //
        $(function () {
            init_selectTable();
        });
        function init_selectTable() {
            // var tbSelecct=document.getElementById("setTable");
            //additemtoselect(xmlSelecct,'空','');
            $.ajax({
                type: "POST",
                url: "TableData.aspx/GetTableNames", //获取主表信息
                data: "{}",
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    formatSelectTable(data.d);
                },
                error: function (err) {
                    alert(err + "err");
                }
            });


        }
        function formatSelectTable(data) {
            if (data) {
                var person = JSON.parse(data);
                var tbSelecct = document.getElementById("setTable")
                //additemtoselect(tbSelecct, '空', '');
                $.each(person, function (n, value) {
                    //do something here   
                    additemtoselect(tbSelecct, value.TableName, value.TableName);
                });
            }

        }
        function additemtoselect(objselect, objitemtext, objitemvalue) {
            var varitem = new Option(objitemtext, objitemvalue);
            objselect.options.add(varitem);
        }

        //格式化字段信息
        var formatField = function (elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\"  name='FieldName' onchange='ChangeEvent(this);'>";
        };



        //arrCanNull
        //格式化是否为空信息
        var formatCanNull = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            var id = "id" + Math.random();
            str1.push("<select id='" + id + "' onchange='ChangeEvent(this);' name='CanNull'>");
            for (i = 0; i < arrCanNull.length; i++) {
                if (arrCanNull[i].Value == sData) {
                    str1.push("<option value='" + arrCanNull[i].Value + "' selected>" + arrCanNull[i].Text + "</option>");
                } else {
                    str1.push("<option value='" + arrCanNull[i].Value + "'>" + arrCanNull[i].Text + "</option>");
                }
            }
            str1.push("</select>");
            elCell.innerHTML = str1.join("");
        }
        //格式化数据类型信息
        var formatCType = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            var id = "id" + Math.random();
            str1.push("<select id='" + id + "' onchange='ChangeEvent(this);' name='CType'>");
            for (i = 0; i < arrCType.length; i++) {
                if (arrCType[i].Value == sData) {
                    str1.push("<option value='" + arrCType[i].Value + "' selected>" + arrCType[i].Text + "</option>");
                } else {
                    str1.push("<option value='" + arrCType[i].Value + "'>" + arrCType[i].Text + "</option>");
                }
            }
            str1.push("</select>");
            elCell.innerHTML = str1.join("");
        }
        //格式化控件类型信息
        var formatControlsType = function (elCell, oRecord, oColumn, sData) {
            var str1 = [];
            var id = "id" + Math.random();
            str1.push("<select id='" + id + "' onchange='ChangeEvent(this);' name='ControlsType'>");
            for (var j = 0; j < arrOperation.length; j++) {
                if (arrOperation[j].Value == sData) {
                    str1.push("<option value='" + arrOperation[j].Value + "' selected>" + arrOperation[j].Text + "</option>");
                } else {
                    str1.push("<option value='" + arrOperation[j].Value + "'>" + arrOperation[j].Text + "</option>");
                }

            }
            str1.push("</select>");
            elCell.innerHTML = str1.join("");
        }

        var formatCheckBoxText = function (elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = "<input type=\"checkbox\" value=\"" + sData + "\"  name='iSun_Selected' >";
        }

        //格式化排序信息
        var formatColSeqText = function (elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\"  name='ColSeq' onchange='ChangeEvent(this);'>";
        }
        //格式化字段名信息
        var formatColDescText = function (elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\"  name='ColDesc' onchange='ChangeEvent(this);'>";
        }
        //格式化字段值信息
        var formatColNameText = function (elCell, oRecord, oColumn, sData) {
            elCell.innerHTML = "<input type=\"text\" value=\"" + sData + "\"  name='ColName' onchange='ChangeEvent(this);'disabled>";
        }


        var myDataSource;
        //YAHOO创建表
        YAHOO.util.Event.addListener(window, "load", function () {
            YAHOO.example.RowDataMod = function () {

                //定义表头
          
                var myColumnDefs = [
            { key: "iSun_Selected", label: "", resizeable: true, formatter: formatCheckBoxText },
            { key: "ColDesc", label: "字段名", resizeable: true, formatter: formatColDescText },
            { key: "ColName", label: "字段值", resizeable: true, formatter: formatColNameText },
            { key: "CType", label: "数据类型", resizeable: true, formatter: formatCType },
            { key: "CanNull", label: "是否必填", resizeable: true, formatter: formatCanNull },
            { key: "ControlsType", label: "控件类型", resizeable: true, formatter: formatControlsType },
            { key: "ColSeq", label: "排序", resizeable: true, formatter: formatColSeqText }
          ];
               

                //定义数据源字段名
                myDataSource = new YAHOO.util.DataSource([]);
                myDataSource.responseType = YAHOO.util.DataSource.TYPE_JSARRAY;
                myDataSource.responseSchema = {
                    fields: ["EntityName", "ColSeq", "ColName", "ColDesc", "CType", "CanNull", "ControlsType", "iSun_Selected"]
                };

                //创建表
                var myDataTable = new YAHOO.widget.DataTable("container",
                myColumnDefs, myDataSource, { selectionMode: "single" });
                mDataTable = myDataTable;
                var i = 1,
            bReverseSorted = false;

                //排序
                // Track when Column is reverse-sorted, since new data will come in out of order
                var trackReverseSorts = function (oArg) {
                    bReverseSorted = (oArg.dir === YAHOO.widget.DataTable.CLASS_DESC);
                };

                //注册事件
                myDataTable.subscribe("rowMouseoverEvent", myDataTable.onEventHighlightRow);
                myDataTable.subscribe("rowMouseoutEvent", myDataTable.onEventUnhighlightRow);
                myDataTable.subscribe("rowClickEvent", myDataTable.onEventSelectRow);
                //            this.myDataTable.subscribe("rowDblclickEvent", onRowDoubleClick);
                myDataTable.subscribe("checkboxClickEvent", function (oArgs) {
                    var elCheckbox = oArgs.target;
                    var oRecord = this.getRecord(elCheckbox);
                    oRecord.setData("iSun_Selected", elCheckbox.checked);
                });

                // Add/update/delete rows as indicated
                var handleClick = function () {
                    // Reset sort
                    myDataTable.set("sortedBy", null);

                    index = myDataTable.getRecordSet()._records.length;
                    var entity = const_BlankInstance;
                    myDataTable.addRows(entity, index);

                    YAHOO.log("Could not continue due to invalid index.");
                }


                var fnDelete = function () {
                    var recordID = myDataTable.getSelectedRows()[0];
                    myDataTable.deleteRow(recordID);
                    //alert(recordID);
                }

                //保存
                var Save = function () {
                    //setQuery();
           
                    var errMsg = checkValue();
                    if (errMsg == '') {
                        var fromName = $("#txtFormName").val();
                        var list = myDataTable.getRecordSet()._records;
                        var elist = [];
                        for (var i = 0; i < list.length; i++) {
                            var item = list[i]._oData;
                            var isSelect = list[i]._oData.iSun_Selected;
                            if (isSelect == "false") { isSelect = false; }
                            if (isSelect) {
                                elist.push(item);
                            }
                        }
                        elist = jlinq.from(elist).sort('ColSeq').select();
                        url = "index.aspx";
                        var jsonStr = YAHOO.lang.JSON.stringify(elist);
                        //var condition = getCondition();

                        //QueryInstance[0].EntityOjbectList = jsonStr;
                        //生成数据
                        //jsonStr =  YAHOO.lang.JSON.stringify(QueryInstance[0]);
                        //alert(jsonStr);formname

                        //var SaveUrl = url + "?r=" + Math.random() + "&action=CreateForm&table=" + const_EntityName + "&formname=" + fromName + "&json=" + encodeURI(jsonStr.replace(/&/g, "[A]").replace(/'/g, "''"));
                        //window.location.href = SaveUrl;
                        //_FormID = NewGuid();
                        _FormName = fromName;
                        _MasterTableName = const_EntityName;
                        //formName, masterTableName, strJson
                        if (typeof (jsonStr) != "undefined") {
                            //<div id="container">
                            //$("#yuievtautoid-0").html("");
                            $("#contents").remove();
                            document.getElementById('divEditor').style.display = '';
                 
                            createEditor(_FormName, _MasterTableName, jsonStr);
                        }


                    }
                    else { alert(errMsg); }
                }

                //var SaveUrl = "index.aspx?r=" + Math.random() + "&action=EditForm&formid={0}" 

                //            var btnAdd = new YAHOO.widget.Button("btnAddNew");
                //            btnAdd.on("click", handleClick);
                var btnSave = new YAHOO.widget.Button("btnSave");
                btnSave.on("click", Save);
                SetFormValue(); fnCreateChkAllCheckBox();
                return {
                    ds: myDataSource,
                    dt: myDataTable
                };

            } ();
        });

        var fnChkAll = function () {
            var ck = $("input[type=checkbox]");
            for (var i = 0; i < ck.length; i++) {
                if (ck[i].type == "checkbox") {
                    ck[i].checked = document.getElementById("chkAll").checked;
                    if (mDataTable._oRecordSet._records[i] != undefined) {
                        mDataTable._oRecordSet._records[i]._oData.iSun_Selected = ck[i].checked;
                    }
                }
            }
        }
        var fnCreateChkAllCheckBox = function () {

            if ((document.getElementById("chkAll")) == null) {

                var e1 = window.document.getElementById("yui-dt0-th-iSun_Selected");
                if (e1 == null) {
                    e1 = window.document.getElementById("yui-dt0-th-iSun_Selected");
                }
                if (e1 == null) {
                    return;
                }
                if (typeof (e1) != "undefined") {
                    var in1 = e1.firstChild;
                    var el = document.createElement("input");
                    el.setAttribute("type", "checkbox");
                    el.setAttribute("id", "chkAll");
                    el.setAttribute("onclick", "fnChkAll()");
                    el.setAttribute("style", "margin-left:0px;margin-top:0px;z-index:200")
                    in1.insertBefore(el);
                }
            }
        }
        var txtFormName_ChangeEvent = function (obj) {
            if (checkIsEmpty(obj)) {
                alert("您输入的表单名为空！请重新输入。");
            }

        }
        var checkValue = function () {
            var ErrMsg = '';
            var formName = document.getElementById("txtFormName");
            var setTable = document.getElementById("setTable");
            if (checkIsEmpty(formName)) { ErrMsg = "您输入的表单名为空！请重新输入."; }
            if (checkIsEmpty(setTable)) { ErrMsg = ErrMsg + "您选择入的表名为空！请重新选择."; }

            return ErrMsg;
        }
        var checkIsEmpty = function (obj) {
            var text = obj.value
            var isEmpty = false;
            if (text == '') { isEmpty = true; }
            else { isEmpty = false; }
            return isEmpty;
        }

        var setTable_ChangeEvent = function (oArgs) {
            var f = oArgs.name;
            //alert(f);
            var v = oArgs.value;
            //alert(v);
            if (v == '') { alert("您选择入的表名为空！请重新选择。"); }
            else {
                const_EntityName = v;
                getTableField(v);
            }
        }

        var getTableField = function (v) {
            var _currentParams = {
                TableName: v
            };
            $.ajax({
                type: "POST",
                url: "TableData.aspx/getTableField", //获取主表信息
                data: JSON.stringify(_currentParams),
                contentType: "application/json; charset=utf-8",
                dataType: "json",
                success: function (data) {
                    if (data) {
                        if (data.d) {
                            const_SolutionList = data.d;
                            SetFormValue();
                        }
                    }
                },
                error: function (err) {
                    alert(err + "err");
                }
            });
        }

        //值改变事件
        var ChangeEvent = function (oArgs) {
            var f = oArgs.name;
            //alert(f);
            var v = oArgs.value;
            //alert(v);
            setValue(f, v);
        }

        ///f=字段名 v=值
        var setValue = function (f, v) {
            var recordID = mDataTable.getSelectedRows()[0];
            var record = mDataTable.getRecord(recordID);
            record._oData[f] = v;
        }


        var ChangeSolution = function (obj) {
            //alert(obj.value);
            for (var i = 0; i < const_SolutionList.length; i++) {
                if (const_SolutionList[i].QueryId == obj.value) {
                    SetFormValue(const_SolutionList[i]);
                }
            }

            //const_SolutionList 
        }

        var SetFormValue = function () {

            var arr = const_SolutionList;
            if (arr != null) {
                myDataSource.liveData = arr;
                mDataTable.getDataSource().sendRequest(null,
        { success: mDataTable.onDataReturnInitializeTable },
        mDataTable);
            }
            // mDataTable.render();
            // document.getElementById("SolutionName").value = obj.SolutionName;
            // document.getElementById("IsDefault").checked = QueryInstance[0].IsDefault == "Y" ? true : false;
        }

    
    </script>
    
       </form>
</body>
</html>
